<!--  -->
<template>
  <div>
    <table style="width:800px" border>
      <thead>
        <tr>
          <th>名称</th>
          <th>数量</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr :key="index" v-for="(item, index) in data">
          <td align="center">{{ item.name }}</td>
          <td align="center">
            <button @click="addNum(item, 'delete')">-</button>
            {{ item.num }}
            <button @click="addNum(item, 'add')">+</button>
          </td>
          <td align="center">{{ item.num * item.price }}</td>
          <td align="center">
            <button @click="remove(index)">删除</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td align="center">总价:{{ $total }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue';
// 先定义数据类型
type Shop = {
  name: string,
  num: number,
  price: number
}
// 总数
let $total = ref(0)
const data = reactive<Shop[]>([
  {
    name: "sy的丝袜",
    num: 1,
    price: 100
  },
  {
    name: "sy的衣服",
    num: 1,
    price: 100

  },
  {
    name: "sy的裤子",
    num: 1,
    price: 100

  }
])

// 添加和删除数量
const addNum = (item: Shop, type: string): void => {

  if (item.num > 1 && type === 'delete') {
    item.num--

  }
  if (item.num <= 99 && type === 'add') {
    item.num++
  }
  addPrice()

}

// 删除方法
const remove = (index: number): void => {
  data.splice(index, 1)
  addPrice()
}

// 计算总价 也可以写成计算属性
/*
 $total=computed<number>(()=>{
   data.reduce((prev, cru) => {
    return prev + (cru.num * cru.price)
  }, 0)
 })
*/
const addPrice = () => {
  $total.value = data.reduce((prev, cru) => {
    return prev + (cru.num * cru.price)
  }, 0)
}
addPrice()
</script>
<style scoped>
</style>